<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Twitter Scheduler Controller
 *
 * PHP version 5
 * LICENSE: This source file is subject to LGPL license
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/copyleft/lesser.html
 * @author     Ushahidi Team <team@ushahidi.com>
 * @package    Ushahidi - http://source.ushahididev.com
 * @module     Twitter Controller
 * @copyright  Ushahidi - http://www.ushahidi.com
 * @license    http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License (LGPL)
*/

class Facebookposts_Controller extends Controller {

	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		// Grabbing tweets requires cURL so we will check for that here.
		if (!function_exists('curl_exec'))
		{
			throw new Kohana_Exception('twitter.cURL_not_installed');
			return false;
		}

		// Retrieve Current Settings
		$settings = ORM::factory('settings', 1);

		// Retrieve Last Stored date
		$last_date = "";
		$t = ORM::factory('facebookposts_settings')
			->find();
		if ($t->loaded == true)
		{
			$last_date = "&since=" . $t->since_date;
		}

		//Retrieve wall posts
        $graph_url = "https://graph.facebook.com/".Kohana::config('facebookposts.fb_page_id')."/feed?limit=250".$last_date;
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $graph_url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 60); //Since Facebook is not down a lot, set timeout to 60 secs
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); //Set curl to store data in variable instead of print
        $buffer = curl_exec($curl_handle);
        curl_close($curl_handle);
		
		//print_r($buffer);
		
        $this->add_wall_posts($buffer); //if FALSE, we will drop out of the loop

	}

	/**
	* Adds wall posts in JSON format to the database and saves the sender as a new
	* Reporter if they don't already exist
    * @param string $data - Facebook posts JSON results
    */
	private function add_wall_posts($data)
	{
		$services = new Service_Model();
		$service = $services->where('service_name', 'Facebookposts')->find();
	   	if (!$service) {
 			return;
		}
		$post_data = json_decode($data, true);
		
		//print_r($post_data);
		
		$posts = $post_data['data'];
		
		
		if (!$posts) {
			echo "Post is empty";
			
			return;
		}
		if (empty($posts)) {
			echo "Post is empty";
			return;
		}
		
		//print_r($posts);

		//$tweet_results = $tweets->{'results'};

		foreach($posts as $post) {
			
		 	print_r("").'<br/><br/>';
			
			print_r($post['from']['id']);
			echo '<br/><br/>';
			
			if($post['from']['id'] == Kohana::config('facebookposts.fb_page_id')){
				echo  'Ignoring wall post form page: '.$post['message'];
				echo '<br/><br/>';
				
				continue;
			}
			
			
			
			$reporter = ORM::factory('reporter')
				->where('service_id', $service->id)
				->where('service_account', $post['from']['name'])
				->find();

			if (!$reporter->loaded)
			{
	    		// get default reporter level (Untrusted)
				$level = ORM::factory('level')
					->where('level_weight', 0)
					->find();

				$reporter->service_id	   = $service->id;
				$reporter->level_id			= $level->id;
				$reporter->service_userid   = null;
				$reporter->service_account  = $post['from']['name'];
				$reporter->reporter_first   = null;
				$reporter->reporter_last	= null;
				$reporter->reporter_email   = null;
				$reporter->reporter_phone   = null;
				$reporter->reporter_ip	  = null;
				$reporter->reporter_date	= date('Y-m-d');
				$reporter->save();
			}

			if ($reporter->level_id > 1 &&
				count(ORM::factory('message')->where('service_messageid', $post['id'])
									   ->find_all()) == 0) {
				// Save Tweet as Message
				$message = new Message_Model();
				$message->parent_id = 0;
				$message->incident_id = 0;
				$message->user_id = 0;
				$message->reporter_id = $reporter->id;
				$message->message_from = $post['from']['name'];
				$message->message_to = null;
				$message->message = $post['message'];
				$message->message_type = 1; // Inbox
				$post_date = date("Y-m-d H:i:s",strtotime($post['created_time']));
				$message->message_date = $post_date;
				$message->service_messageid = $post['id'];
				$message->save();
			}
			
			
		}
		
		echo $post_data['paging']['previous'];
		echo '<br/><br/>';
		$search = "https://graph.facebook.com/".Kohana::config('facebookposts.fb_page_id')."/feed?limit=250&since=";
		echo $search;
		echo '<br/><br/>';
		$since = str_ireplace($search, "", $post_data['paging']['previous']);
			
			$this->db =  new Database();
			
			
			
			$this->db->query("
				UPDATE `".Kohana::config('database.default.table_prefix')."facebookposts_settings` 	
				SET `since_date` = '$since';
			");
	}
}
